package com.example.springboot.config;

import com.example.springboot.security.*;
import com.example.springboot.utils.AjaxRequestMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UrlUserService urlUserService;
    @Autowired
    SessionRegistry sessionRegistry;

    @Autowired
    private AjaxAuthenticationEntryPoint ajaxAuthenticationEntryPoint;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.csrf() // 跨站
                .disable() // 关闭跨站检测
                .authorizeRequests() // 验证策略
                .antMatchers("/logout").permitAll()
                .antMatchers("/favicon.ico", "/assert/**", "/html/**").permitAll().anyRequest() // 所有请求
                .authenticated() // 必须验证
                .and().formLogin().loginPage("/login").failureUrl("/login?error")// 自定义登录页
                .successHandler(getLoginSuccHandler()).failureHandler(getFailureHandler()).permitAll()
                // .defaultSuccessUrl("/welcome", true) // 登录成功后跳转页
                .permitAll().and().exceptionHandling().accessDeniedHandler(getAccessDeniedHandler()).
                defaultAuthenticationEntryPointFor(ajaxAuthenticationEntryPoint, new AjaxRequestMatcher());

    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }

    @Bean
    public AccessDeniedHandler getAccessDeniedHandler() {
        return new RestAuthenticationAccessDeniedHandler();
    }

    @Bean
    public LoginSuccHandler getLoginSuccHandler() {
        LoginSuccHandler handler = new LoginSuccHandler();
        return handler;
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setHideUserNotFoundExceptions(false);
        provider.setUserDetailsService(urlUserService);
        provider.setPasswordEncoder(new PasswordEncoder() {

            @Override
            public String encode(CharSequence rawPassword) {
                return (String) rawPassword;
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                // 传过来的密码和数据库的密码
                return encodedPassword.equals(rawPassword);
            }
        });
        return provider;
    }

    @Bean
    public LoginFailureHandler getFailureHandler() {
        LoginFailureHandler handler = new LoginFailureHandler();
        return handler;
    }

    @Bean
    public SessionRegistry getSessionRegistry() {
        SessionRegistry sessionRegistry = new SessionRegistryImpl();
        return sessionRegistry;
    }


}